package com.lcf.framework.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lcf.framework.utils.ServletUtils;
import com.lcf.framework.utils.UserUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.lcf.framework.constant.SysConstant.DEFAULT_DELETED;
import static com.lcf.framework.constant.SysConstant.DEFAULT_VERSION;

/**
 * 描述：字段自动填充
 *
 * @author lcf
 * @since 2025/2/23 13:23
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasSetter("createBy")) {
            this.strictInsertFill(metaObject, "createBy", Long.class, ServletUtils.getRequest() != null && StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 0L);
        }
        if (metaObject.hasSetter("tenantId")) {
            this.strictInsertFill(metaObject, "tenantId", Long.class, UserUtils.getTenantId());
        }
        if (metaObject.hasSetter("version")) {
            this.strictInsertFill(metaObject, "version", Integer.class, DEFAULT_VERSION);
        }
        if (metaObject.hasSetter("delFlag")) {
            this.strictInsertFill(metaObject, "delFlag", Integer.class, DEFAULT_DELETED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter("updateTime")) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasSetter("updateBy")) {
            this.strictUpdateFill(metaObject, "updateBy", Long.class, ServletUtils.getRequest() != null && StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 0L);
        }
    }
}
